package com.jt808.decode.utils;

import com.jt808.decode.model.DeviceParam;
import com.jt808.decode.model.Jt808Message;
import io.netty.buffer.ByteBuf;

import java.util.HashMap;
import java.util.Map;

/**
 * Query terminal parameter response
 * @author HyoJung
 * @date 20230303
 */
public class Message0104Parser {

    /**
     * Query terminal parameter response
     * @param msg
     * @param msgBodyBuf
     * @return
     */
    public static DeviceParam parse(Jt808Message msg, ByteBuf msgBodyBuf){
        //Response serial number
        int replyMsgFlowId = msgBodyBuf.readUnsignedShort();
        //Number of response parameters
        int itemCount = msgBodyBuf.readUnsignedByte();
        //Parameter item map
        ByteBuf itemContentBuf = null;
        Map<String, Object> itemMap = new HashMap<>();
        while (msgBodyBuf.readableBytes() >= 5) {
            int itemId = Math.toIntExact(msgBodyBuf.readUnsignedInt());
            int itemLen = msgBodyBuf.readUnsignedByte();
            if (msgBodyBuf.readableBytes() < itemLen) {
                break;
            }
            itemContentBuf = msgBodyBuf.readSlice(itemLen);
            Class<?> itemType = Jt808ParamUtil.getParamType(itemId);
            if (itemType == Integer.class) {
                itemMap.put(NumberUtil.formatMessageId(itemId), itemContentBuf.readInt());
            } else if (itemType == Short.class) {
                itemMap.put(NumberUtil.formatMessageId(itemId), itemContentBuf.readShort());
            } else if (itemType == Byte.class) {
                itemMap.put(NumberUtil.formatMessageId(itemId), itemContentBuf.readByte());
            } else if (itemType == String.class) {
                String itemStr = CommonUtil.readGbkString(itemContentBuf, itemLen);
                itemMap.put(NumberUtil.formatMessageId(itemId), itemStr);
            } else {
                byte[] itemArr = new byte[itemLen];
                itemContentBuf.readBytes(itemArr);
                itemMap.put(NumberUtil.formatMessageId(itemId), itemArr);
            }
        }
        DeviceParam deviceParam=new DeviceParam();
        deviceParam.setTerminalNum(msg.getPhoneNumber());
        deviceParam.setHexMsgId(NumberUtil.formatMessageId(msg.getMsgId()));
        deviceParam.setMsgFlowId(msg.getMsgFlowId());
        deviceParam.setReplyMsgFlowId(replyMsgFlowId);
        deviceParam.setItemCount(itemCount);
        deviceParam.setItemMap(itemMap);
        return deviceParam;
    }
}
